package vn.vnu.uet.email;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Properties;

import javax.mail.Folder;
import javax.mail.Session;
import javax.mail.Store;

import vn.vnu.uet.email.R;
import vn.vnu.uet.email.bean.User;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.AdapterView.OnItemClickListener;

public class Inbox extends DefaultActivity {

	ListView listContent;
	ArrayList<HashMap<String, String>> listItem = new ArrayList<HashMap<String, String>>();
	HashMap<String, String> map = new HashMap<String, String>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState, R.layout.score);

		new ProgressTask(Inbox.this).execute(Token.instance().host,
				Token.instance().mailStoreType, Token.instance().user.userName,
				Token.instance().user.password);
		Button delete = (Button) findViewById(R.id.delete);
		delete.setText("Cập nhật");
		// delete.setVisibility(View.GONE);
		delete.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				restartActivity();
			}
		});

		this.setTitle("Danh sách Email");
	}

	protected class ProgressTask extends AsyncTask<String, Void, Boolean> {
		private ProgressDialog dialog;

		ProgressTask(Context c) {
			super();
			dialog = new ProgressDialog(c);
		}

		protected void onPreExecute() {
			this.dialog.setMessage("Đang tải....Email \nVui lòng đợi!");
			this.dialog.show();
		}

		protected void onPostExecute(final Boolean success) {

			if (dialog.isShowing()) {
				dialog.dismiss();
				SimpleAdapter mSchedule = new SimpleAdapter(Inbox.this,
						listItem, R.layout.row3,
						new String[] { "score", "name" }, new int[] {
								R.id.score, R.id.name });
				listContent.setAdapter(mSchedule);
				listContent.setOnItemClickListener(new OnItemClickListener() {
					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1,
							int position, long arg3) {
						Intent intent = new Intent(Inbox.this, ViewContent.class);
						intent.putExtra("index", position);
						startActivity(intent);
					}
				});
			}
		}

		protected Boolean doInBackground(final String... args) {
			try {
				String host = args[0];// change accordingly
				String mailStoreType = args[1];
				String username = args[2];
				String password = args[3];// change accordingly

				// receiveEmail(host, mailStoreType, username, password);
				Properties properties = System.getProperties();
				properties.setProperty("mail.pop3.disabletop", "true");

				// properties.put("mail.pop3.host", host);
				Session emailSession = Session.getDefaultInstance(properties);

				Store emailStore = emailSession.getStore(mailStoreType);
				try {
					emailStore.connect(host, username, password);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				Folder emailFolder = emailStore.getFolder("INBOX");
				emailFolder.open(Folder.READ_ONLY);
				System.out.println("---------------------");

				Token.instance().user = new User(null, username, null, null,
						null, username + "@vnu.edu.vn", password);
				messages = emailFolder.getMessages();
				Token.instance().messages = messages;

				listContent = (ListView) findViewById(R.id.listContent);

				for (int i = 0; i < 30; i++) {
					map = new HashMap<String, String>();
					map.put("score",
							convertEmail(messages[i].getFrom()[0].toString()));
					map.put("name", messages[i].getSubject());
					listItem.add(map);
				}
				Token.instance().folder = emailFolder;
				Token.instance().store = emailStore;
				emailFolder.close(false);
				emailStore.close();
				return true;
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return false;
			}
		}
	}

	public void restartActivity() {

		Intent intent = getIntent();

		finish();
		startActivity(intent);

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			DefaultActivity.createConfirmDialog(Inbox.this, "Thoát",
					"Bạn có muốn đăng xuất không?", new DialogCallback() {
						public void onOkClick() {
							Token.clear();
							ViewController.showLoginScreen(Inbox.this);
						}
					}, null);

			return true;
		}

		return super.onKeyDown(keyCode, event);
	}

}
